package com.aos.util;


import org.apache.tomcat.util.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;


public class Base64Utils {
	
	private static Logger log = LoggerFactory.getLogger(Base64Utils.class);
	
    /** 
     * 文件读取缓冲区大小
     */
    private static final int CACHE_SIZE = 1024;

    
    /**  
     * 二进制数据编码为BASE64字符串
     *
     * @param bytes
     * @return
     * @throws Exception
     */
    public static String encode(byte[] bytes) throws Exception {
        return Base64.encodeBase64String(bytes);
    }

    /**  
     * 将文件编码为BASE64字符串
     * 大文件慎用，可能会导致内存溢出
     *
     * @param filePath 文件绝对路径
     * @return
     * @throws Exception
     */
    public static String encodeFile(String filePath) throws Exception {
        byte[] bytes = fileToByte(filePath);
        return encode(bytes);
    }
    
    /** 
     * BASE64字符串解码为二进制数据
     *
     * @param base64
     * @return
     * @throws Exception
     */
    public static byte[] decode(String base64) throws Exception {
        return Base64.decodeBase64(base64.getBytes());
    }
    
    
    /**  
     * BASE64字符串转回文件
     *
     * @param filePath 文件绝对路径
     * @param base64 编码字符串
     * @throws Exception
     */
    public static void decodeToFile(String filePath, String base64) throws Exception {
        byte[] bytes = decode(base64);
        byteArrayToFile(bytes, filePath);
    }

   
    
    /** 
     * 文件转换为二进制数组
     *
     * @param filePath 文件路径
     * @return
     * @throws Exception
     */
    public static byte[] fileToByte(String filePath) throws Exception {
        byte[] data = new byte[0];
        FileInputStream in = null;
        ByteArrayOutputStream out = null;
        try {
        	 File file = new File(filePath);
             if (file.exists()) {
                 in = new FileInputStream(file);
                 out = new ByteArrayOutputStream();
                 byte[] cache = new byte[CACHE_SIZE];
                 int nRead = 0;
                 while ((nRead = in.read(cache)) != -1) {
                     out.write(cache, 0, nRead);
                     out.flush();
                 }
                 data = out.toByteArray();
             }
		} catch (Exception e) {
			log.error("文件转换为二进制数组错误：", e);
		} finally {
			if(out != null){
				try {
					out.close();
				} catch (IOException e2) {
					log.error("关闭流错误：", e2);
				}
			}
			if(in != null){
				try {
					in.close();
				} catch (IOException e2) {
					log.error("文件转换为二进制数组关闭流错误：", e2);
				}
			}
		}
       
        return data;
    }

    /** 
     * 二进制数据写文件
     *
     * @param bytes 二进制数据
     * @param filePath 文件生成目录
     */
    public static void byteArrayToFile(byte[] bytes, String filePath) throws Exception {
        InputStream in = new ByteArrayInputStream(bytes);
        OutputStream out = null;
        try {
        	 out = new FileOutputStream(new File(filePath));
             byte[] cache = new byte[CACHE_SIZE];
             int nRead = 0;
             while ((nRead = in.read(cache)) != -1) {
                 out.write(cache, 0, nRead);
                 out.flush();
             }
             out.close();
             in.close();
		} catch (Exception e) {
			log.error("二进制数据写文件错误：", e);
		} finally {
			if(out != null){
				try {
					out.close();
				} catch (IOException e2) {
					log.error("文件转换为二进制数组关闭流错误：", e2);
				}
			}
		}
    }
    
    
    /**
     * bytes转换成十六进制字符串
     * @param b
     * @return
     */
	public static String byte2HexStr(byte[] b) {
		if (b == null){
			return "";
		}
		StringBuilder hs = new StringBuilder();
		String stmp = "";
		for (int n = 0; n < b.length; n++) {
			stmp = (Integer.toHexString(b[n] & 0XFF));
			if (stmp.length() == 1) {
				hs.append("0" + stmp);
			} else {
				hs.append(stmp);
			}
		}
		return hs.toString().toUpperCase();
	}
	 
}
